var api = require('../../../utils/api.js')
var $ = require('../../../utils/util.js')
var regeneratorRuntime = require('../../../utils/runtime.js')
var app = getApp()
var Store = app.Store 

Page({
  data: {
    info:'',
    isShowTime: false, // 是否显示时间弹框
    isShowPicker:false, // 是否显示选择项
    key_picker: '', // piker需要的字段


    user_name: 0, // 用户id(告警独有)
    rec: '',// 编号外部传进来(告警独有)
    id: '', //缺陷独有（有的时候是修改）
    ticket_num: '', //检修和巡检独有
    report_id: 0,//	为空则添加数据
    company: '', // 企业用户
    company_id: '', // 企业id
    factory: '', // 厂站名称
    equipment: '', // 缺陷设备名称
    equipType: '', // 设备类型
    voltageLevel: '', // 电压等级
    standard: '', // 缺陷标准
    defectGrade: '', // 缺陷性质
    defectFinder: '', // 缺陷发现人
    defectFinder_id: '', // 缺陷发现人用户表id
    phone: '', // 联系电话
    findDate: '', // 缺陷发现时间
    defectType: '', // 设备类 和 非设备类
    mainEquipImage: '', // 主设备图片
    partEquipImage: '', // 局部设备图片
    nameplateImage: '', // 设备铭牌图片
    content: '', // 缺陷内容
    deal: '', // 缺陷安排处理 0需要安排处理；2直接消缺
    submit: '', // 保存0；提交1 
 
    defectArr: [{ type: 0, text: '设备类' }, { type: 1, text: '非设备类' },], //  设备类型
    dealArr: [{ type: 0, text: '需要安排处理' }, { type: 2, text: '直接消缺' },], //  缺陷安排处理 0需要安排处理；2直接消缺
    defectStyle: 0, // 配置参数
    dealIndex: 0, // 配置的参数
    
    pinkColumns:[], // pink 数据
    pinkIndex:'', // 当前的index
    companySelected: {}, //公司选择后的数据
    stationSelected: {}, //厂站选择后的数据
    type: 2, // 类型 0:告警--缺陷 1:报修-缺陷 2: 缺陷--更新和添加

    url: [
      api.warningManage.setDefect, // 0:告警--缺陷 
      api.repairsManage.setDefectByrepair, // 1:报修-缺陷
      api.defect.update, //2: 缺陷--更新和添加
      api.checkManage.setDefectBycheck, //3: 检修--缺陷
      api.robManage.setDefectByrob,//4: 抢修-缺陷
      api.pollingManage.setDefectBypatrolplan,//5: 巡检-缺陷
    ],
    source:'', // 缺陷名字
    sources: ['告警', '报修', '','检修'], // 默认进来的
    sourceArr: [ // 缺陷来源
      { type: 0, text: '告警' }, 
      { type: 1, text: '巡检' },
      { type: 2, text: '报修' },
      { type: 3, text: '抢修' },
      { type: 4, text: '检修' }
    ], //  设备类型
    sourceIndex:0, 
    isUpdata: 0, // 是否更新

  },
  onLoad: function (options) { 
    Store.dispatch({
      type: 'SET_FROM',
      form: {

      }, 
    })

    if ('type' in options){ 
      this.setData({
        type: options.type, // 区分接口
        findDate: $.transformTime(),
        source: this.data.sources[options.type]
      })
    }

    if ('isUpdata' in options){
      this.setData({
        isUpdata: options.isUpdata
      })
    }

    if ('info' in options){ 
      var info = JSON.parse(options.info)  
      console.log(info, '$$info$$')
      this.setData({
        info:info,
        user_name: wx.getStorageSync('user_name'),  // 告警独有
        rec: info._id|| info.id || '', // 告警独有
        report_id: info.id||'', // 报修独有
        number: info.number || '', //缺陷独有（有的时候是修改）
        ticket_num: info.ticket_num || info._id ||'', //检修和巡检独有
        dept_id:info.dept_id || '',
        company: info.company || info.companyName || '',
        company_id: info.company_id || '',
        factory: info.factory || info.cm || info.factoryName ||'',
        factory_id:info.STATIONID ||info.ch ||info.factory_id ||'',
        equip_id:info.equip_id || '',
        equip:info.equip  || info.line_name || info.xlm || '',
        equipment: info.equipment || info.line_name || info.equip|| info.xlm ||'',
        equipType: info.equip?info.equipType : '',
        voltageLevel: info.equip?info.voltageLevel : '',
        standard: info.standard || '',
        defectGrade: info.defectGrade || '',
        source: info.source || '',
        defectFinder: info.defectFinder || wx.getStorageSync('user_name'),
        defectFinder_id: info.defectFinder_id || wx.getStorageSync('user_id'),
        phone: info.phone || wx.getStorageSync('phonenumber'),
        findDate: info.findDate || $.transformTime() || '',
        defectType: info.defectType || '设备类',
        mainEquipImage: info.mainEquipImage || '',
        partEquipImage: info.partEquipImage || '',
        nameplateImage: info.nameplateImage || '',
        content: info.content || '',
        deal: info.deal || '0',   
        submit: info.submit || 0
      })
    } else {
      this.setData({
        defectFinder: wx.getStorageSync('user_name'),
        defectFinder_id:wx.getStorageSync('user_id'),
        phone: wx.getStorageSync('phonenumber'),
      })
    }

    var that=this;
    console.log(this.data.type)
    if($.isNull(this.data.dept_id)){
      if($.isNull(this.data.equipment)){//非设备类
        api.$get(api.auth.findDeptIdBystation,{'name':this.data.factory,'parent_name':this.data.company,}).then((res)=>{
          that.setData({
            dept_id:res.data.dept_id,
            factory_id:res.data.dept_id,
          })
        })
      }else{//设备类
       
        api.$get(api.auth.findDeptIdByEquip,{'parent_name':this.data.factory,'name':this.data.equip}).then((res)=>{
          that.setData({
            dept_id:res.data.dept_id,
            equip_id:res.data.dept_id,
          })


          if($.isNull(that.data.equipType)&& $.isNull(that.data.voltageLevel)){
            api.$get(api.auth.findTypeByequip,{'parent_name':this.data.factory,'name':this.data.equip}).then((res)=>{
              that.setData({
                voltageLevel: res.data.VOLTAGEGRADE,
                equipType:  res.data.RESERVED_S0 || res.data.DEVICETYPE ,
              })
            })
          }
        })
      }

    }else if(!$.isNull(this.data.dept_id)){
      
      api.$get(api.auth.findDeptIdByEquip,{'parent_name':this.data.factory,'name':this.data.equip}).then((res)=>{
        that.setData({
          dept_id:res.data.dept_id,
          equip_id:res.data.dept_id,
        })
        console.log("lllllllllllll")
        api.$get(api.auth.findTypeByequip,{'parent_name':this.data.factory,'name':this.data.equip}).then((res)=>{
          that.setData({
            voltageLevel: res.data.VOLTAGEGRADE,
            equipType: res.data.RESERVED_S0 || res.data.DEVICETYPE ,
          })
        })
      })
    }

    var defectArr = this.data.defectArr  // 处理缺陷类型
    if (this.data.defectType) {
      defectArr.forEach((item, index) => {
        if (item.text == this.data.defectType) {
          this.setData({
            defectStyle: item.type
          })
        }
      })
    }
     
    var dealArr = this.data.dealArr  // 处理缺陷类型 
    dealArr.forEach((item, index) => {
      if (item.type == this.data.deal) {
        this.setData({
          dealIndex: index
        })
      }
    })  
  },

  sourceHanlde(){ // 选择缺陷来源
    this.setData({
      pinkColumns: this.data.sourceArr,
      pinkIndex: this.data.sourceIndex,
      key_picker: 'sourceStyle',
      isShowPicker: true
    })
  },

  onShow(){
    var form = Store.getState().formInfor.form
    var key = form.key
    if (!form.selected) return
    switch (key) {
      case 'selectCompany': // 获取企业信息  
        this.setData({
          companySelected: form.selected,
          company: form.selected.dept_name,
          company_id: form.selected.dept_id,
          dept_id: form.selected.dept_id,
          factory:'',
          equipment:'',
          equip: '',
          voltageLevel: '',
          equipType:'',
        })
        break
      case 'selectStation': // 厂站名称
        this.setData({
          stationSelected: form.selected,
          factory: form.selected.dept_name,
          factory_id: form.selected.dept_id,
          dept_id: form.selected.dept_id,
          equipment:'',
          equip: '',
          voltageLevel: '',
          equipType:'',
        })
        break
      case 'getRepairer': // 获取抢修负责人、 抢修人员 、缺陷发现人 
        switch (form.config.type) {
          case 1: // 抢修负责人 
            this.setData({
              leader: form.selected.user_id
            })
            break;
          case 2: // 抢修人员
            this.setData({
              staff: form.selected.user_id
            })
            break;
          case 3: // 缺陷发现人  
            this.setData({
              phone: form.selected.phonenumber,
              defectFinder: form.selected.user_name,
              defectFinder_id: form.selected.user_id,
            })

            break;
        }
        break
      case 'getDefectStandard': // 获取缺陷标准和性质
        this.setData({ 
          standard: form.selected.location + ':' + form.selected.defect_type,
          defectGrade: form.selected.defect_prop
        })
        break
      case 'selectYcxlm': // 设备名称
        this.setData({
          equip_id:form.selected.dept_id,
          dept_id:form.selected.dept_id,
          equipment: form.selected.YCXLM,
          equip: form.selected.YCXLM,
          equipType: form.selected.DEVICETYPE,
          voltageLevel: form.selected.VOLTAGEGRADE,
        })
        break
    }
  },

  updateHandle(e) {
    console.log()
    if (this.data.company == '') {
      $.toast('请选择企业用户')
    } else if (this.data.factory == '' && this.data.defectStyle==0) {
      $.toast('请选择厂站')
    } else if ($.isNull(this.data.equipment) && this.data.defectType == '设备类'&& this.data.type==2) {
      $.toast('请选择设备')
    } else if (this.data.standard == '') {
      $.toast('请选择缺陷标准')
    } else if (this.data.defectFinder == '') {
      $.toast('请选择缺陷发现人')
    } else if (this.data.defectGrade == '') {
      $.toast('请选择缺陷性质')
    } else if (this.data.type == 2 && this.data.source=='') {
      $.toast('请选择缺陷来源')
    } else if (this.data.content == '') {
      $.toast('请选择缺内容')
    // } else if (this.data.deal==0 && this.data.mainEquipImage=='') {
    //   $.toast('上传主设备图片')
    // } else if (this.data.deal==0 && this.data.partEquipImage == '') {
    //   $.toast('请上传局部照片')
    // } else if (this.data.deal==0 && this.data.nameplateImage == '') {
    //   $.toast('请上传设备铭牌照片')
    }else {
        var equipType=this.data.equipType;
      var { submit } = $.detail(e)
      var params = {
        user_name: this.data.user_name, // 告警独有
        rec: this.data.rec, // 告警独有(没有有用id)
        report_id: this.data.report_id, // 报修独有
        number: this.data.number, // 缺陷独有（有的时候是修改）
        ticket_num: this.data.ticket_num, // 检修和巡检独有
        dept_id:this.data.equipment!=''?this.data.equip_id!=''?this.data.equip_id:this.data.dept_id:this.data.dept_id,
        company: this.data.company,
        cm: this.data.factory,
        equipment: this.data.equipType="非设备类"?this.data.equipment:'',
        equipType: equipType,
        voltageLevel: this.data.voltageLevel,
        standard: this.data.standard,
        defectGrade: this.data.defectGrade,
        defectFinder: this.data.defectFinder,
        defectFinder_id: this.data.defectFinder_id,
        phone: this.data.phone,
        source: this.data.source,
        findDate: this.data.findDate,
        defectType: this.data.defectType,
        mainEquipImage: this.data.mainEquipImage,
        partEquipImage: this.data.partEquipImage,
        nameplateImage: this.data.nameplateImage,
        content: this.data.content,
        deal: this.data.deal,
        dealPerson:  wx.getStorageSync('user_name'),
        dealPerson_id: wx.getStorageSync('user_id'),
        submit
      }
console.log(params)
      api.$post(this.data.url[this.data.type], params).then((res) => {
        $.toast('操作成功')
        setTimeout(() => {
          $.linkurl('', 'back')
        }, 1500)
      })
    } 
  },

  selectCompanyHandle() { // 公司  
    if(this.data.type!=2){
      $.toast("该内容无法修改");
      return
    }
    Store.dispatch({
      type: 'SET_FROM',
      form: {
        key: 'selectCompany', // 后台要的更改字段 
        type: 1, // 表单类型 1： radio  2：select
        config: {
        },
      },
    })
    $.linkurl(`/pages/main/chooseForm/chooseForm`)  
  },

   selectStationHandle() { // 选厂站 
    if(this.data.type!=2){
      $.toast("该内容无法修改");
      return
    }
    if(this.data.info.submit=='1'){
      $.toast("已提交无法修改")
  }else{
            if(this.data.company== ''){
              $.toast('请选择公司')
            }else {
            Store.dispatch({
              type: 'SET_FROM',
              form: {
                key: 'selectStation', // 后台要的更改字段 
                type: 1, // 表单类型 1： radio  2：select
                config: {
                  company: this.data.company, 
                  company_id: this.data.company_id ,
                  dept_id:this.data.company_id
                },
              },
            })
            $.linkurl(`/pages/main/chooseForm/chooseForm`)
          } 
        }
  },

  async selectYcxlmHandle (e) { // 根据厂站获取设备列表 
    if(this.data.type!=2){
      $.toast("该内容无法修改");
      return
    }
    if(this.data.info.submit=='1'){
      $.toast("已提交无法修改")
  }else{
        if (this.data.factory == '') {
          $.toast('请选择厂站')
        } else {
          console.log("======"+this.data.company_id)
          var res = await app._selectStation({dept_id: this.data.company_id, company: this.data.company })
          var result = res.data.find((item) => {
            return item.dept_name == this.data.factory
          }) 
          var { type } = $.detail(e)
          Store.dispatch({
            type: 'SET_FROM',
            form: {
              key: 'selectYcxlm', // 后台要的更改字段 
              type: 1, // 表单类型 1： radio  2：select
              config: {
                station: result.station
              },
            },
          })
          $.linkurl(`/pages/main/chooseForm/chooseForm`)
        } 
      }
  },

  getRepairerCompanyHandle(e) { // 选抢修负责人或者抢修人员
    if(this.data.info.submit=='1'){
      $.toast("已提交无法修改")
  }else{
    var { type } = $.detail(e)
    Store.dispatch({
      type: 'SET_FROM',
      form: {
        key: 'getRepairer', // 后台要的更改字段 
        type: 1, // 表单类型 1： radio  2：select
        config: {
          type // 1 获取负责人；2获取人员；3缺陷发现人
        },
      },
    })
    $.linkurl(`/pages/main/chooseForm/chooseForm`)
  }
  },

  getDefectStandardHandle(e) { // 选抢修负责人或者抢修人员
    if(this.data.info.submit=='1'){
      $.toast("已提交无法修改")
  }else{
    var { type } = $.detail(e)
    Store.dispatch({
      type: 'SET_FROM',
      form: {
        key: 'getDefectStandard', // 后台要的更改字段 
        type: 3, // 表单类型 1： radio  2：select 3:特殊的radio
        config: {
           
        },
      },
    })
    $.linkurl(`/pages/main/chooseForm/chooseForm`)
  }
  },
 
  upPicsHandle(e) { // ##图片组件传出来的数据##
    var { pics, key } = e.detail
    console.log(pics, key)
    this.setData({
      [key]: pics.length>0?pics[0]:[]
    })
   
  },
  
  openTimeHandle(e) { // 打开时间弹框
    if(this.data.info.submit=='1'){
      $.toast("已提交无法修改")
  }else{
      this.setData({
        isShowTime: true
      })
    }
  },
  timeConfirmHandle(e) { // 时间组件传出来的数据
    var { time, key } = e.detail

    this.setData({
      [key]: time
    })
  
    console.log(time, key)
  },

  equipmentHandle(){ // 选择设备类型
    if(this.data.type!=2){
      $.toast('该内容无法修改')
      return
    }
    if(this.data.info.submit=='1'){
        $.toast("已提交无法修改")
        console.log('===============')
    }else{
      this.setData({
        pinkColumns: this.data.defectArr,
        pinkIndex: this.data.defecStyle,
        key_picker: 'defectStyle',
        isShowPicker: true
      })
      if(this.data.defectArr[this.data.defectStyle].type!=0){//非设备类
        this.setData({
          equipment:'',
          voltageLevel: '',
          equipType:'',
        })
      }
    }

  },

  dealHandle(){ // 缺陷安排处理 0需要安排处理；2直接消缺
    this.setData({
      pinkColumns: this.data.dealArr,
      pinkIndex: this.data.dealStyle,
      key_picker: 'dealStyle',
      isShowPicker: true
    })
  },

  pickerConfirmHandle(e) { // 时间组件传出来的数据 
    var { value, key, index } = e.detail
    this.setData({
      [key]: value.type
    })
    switch (key){
      case 'defectStyle': // 设备类型
        this.setData({
          defectType: value.text
        })
        break;
      case 'dealStyle': // 缺陷安排处理
        this.setData({
          deal: value.type,
          dealIndex: index
        })
        break;
      case 'sourceStyle': // 缺陷安排处理
        this.setData({
          sourceIndex: index,
          source: value.text, 
        })
        break;
    }
    console.log(value, key)
  },

  //##input 输入##
  input_handle(e) {
    this.setData({
      [e.currentTarget.dataset.key]: e.detail.value
    })
  },
  //##input 输入##
  toCheckManageAdd(){//转检修
    var data=this.data;
    var info1={
      company:data.company, //'企业用户',
      dept_id:data.dept_id,
      company_id:data.company_id, //'企业用户',
      factory_id:data.factory_id, //'厂站名称',
      factory:data.factory, //'厂站名称',
      equip:data.equip, // '设备名称', 
      number:data.info.number,//缺陷单号
      contact:data.defectFinder, // '联系人',
      phone:data.phone, // '联系电话',
      source:"缺陷"
    }
    $.linkurl( `/pages/checkManage/checkManageAdd/checkManageAdd?type=1&info=${JSON.stringify(info1)}`)
  },
  toRobManage(){//转抢修
    var data=this.data;
    var info1={
      dept_id:data.dept_id,
      company:data.company, //'企业用户',
      company_id:data.company_id, //'企业用户',
      factory_id:data.factory_id, //'企业用户',
      factory:data.factory, //'厂站名称',
      equip:data.equip,
      number:data.info.number,//缺陷单号
      source:"缺陷"
    }
    $.linkurl(`/pages/robManage/robManageRushSend/robManageRushSend?info=${JSON.stringify(info1)}&u_i=3`)
  },
  openLoseHandle() { // 作废弹窗
    this.setData({ isLose: true })
  },
  setZuoFei(){//作废
    if($.isNull(this.data.invalidReason)){
      $.toast("作废原因不能为空")
        return
    }
    var params = {
      "number": this.data.number,
      "state":'已作废',//状态变为 ：已作废
      "invalidReason":this.data.invalidReason,//作废原因
      "invalidPersonid":wx.getStorageSync('user_id'),//作废人id
      "invalidPerson":wx.getStorageSync('user_name'),//作废人
      "cancel":'1',
    }
    console.log(params);
    api.$post(api.defect.setZuoFei, params).then((res) => {
      $.toast('作废成功')
      setTimeout(() => {
        $.linkurl('', 'back')
      }, 1500)
    })
  },
})